package com.bezdelnick.forum.web.component;


import org.apache.wicket.Component;
import org.apache.wicket.markup.html.form.ILabelProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 4/5/12
 * Time: 12:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class FeedbackLabel extends Label implements ILabelProvider{
    public static final String CSS_VALIDATION_ERROR_CLASS = "inlineErrorMessage";

    private static final Logger LOGGER = LoggerFactory.getLogger(FeedbackLabel.class);

    private Component feedbackSource;

    public FeedbackLabel(String id, Component feedbackSource) {
        this(id, new Model<String>(""), feedbackSource);
    }

    private FeedbackLabel(String id, IModel<?> model, Component feedbackSource) {
        super(id, model);
        setOutputMarkupId(true);
        this.feedbackSource = feedbackSource;
    }

    private FeedbackMessage getFeedbackMessageIfPossible() {
        if (feedbackSource.getFeedbackMessage() == null) {
            return null;
        }
        if (feedbackSource.getFeedbackMessage().isRendered()) {
            return null;
        }

        FeedbackMessage fbMessage = feedbackSource.getFeedbackMessage();

        if (feedbackSource.getFeedbackMessage().getMessage() == null) {
            LOGGER.warn("Unable to render component feedback message - it is null! Component is "
                    + feedbackSource.getPath());
        }

        return fbMessage;
    }

    @Override
    protected void onBeforeRender() {
        FeedbackMessage fbMessage = getFeedbackMessageIfPossible();
        if (fbMessage != null) {
            setDefaultModel(new Model<String>(fbMessage.getMessage().toString()));
        } else {
            setDefaultModel(new Model<String>(""));
        }
        //setVisible(fbMessage != null);
        super.onBeforeRender();
    }

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);
        FeedbackMessage fbMessage = getFeedbackMessageIfPossible();
        if (fbMessage == null) return;
        fbMessage.markRendered();
        tag.put("class", CSS_VALIDATION_ERROR_CLASS);
    }

    @Override
    public IModel getLabel() {
        //return null;
        return this.getLabel();
    }
}
